/*
 * lcd_169_st7789v2.c
 *
 *  Created on: Mar 20, 2025
 *      Author: QkLia
 */
#include "lcd_169_st7789v2.h"
#include "spi.h"

void lcd_write_cmd(uint8_t cmd){

	LCD_CS_ON
	LCD_DC_CMD

	HAL_SPI_Transmit(&hspi1, &cmd, 1, 100);
//	HAL_SPI_Transmit_DMA(&hspi1, &cmd, 1);

	LCD_CS_OFF

}

void lcd_write_dat8(uint8_t dat){

	LCD_CS_ON
	LCD_DC_DATA

	HAL_SPI_Transmit(&hspi1, &dat, 1, 100);
//	HAL_SPI_Transmit_DMA(&hspi1, &dat, 1);

	LCD_CS_OFF

}

void lcd_write_dat16(uint16_t dat){

	LCD_CS_ON
	LCD_DC_DATA

	uint8_t temp = dat >> 8;
	HAL_SPI_Transmit(&hspi1, &temp, 1, 100);
//	HAL_SPI_Transmit_DMA(&hspi1, &temp, 1);
	temp = dat;
	HAL_SPI_Transmit(&hspi1, &temp, 1, 100);
//	HAL_SPI_Transmit_DMA(&hspi1, &temp, 1);

	LCD_CS_OFF

}

void lcd_init(){

	LCD_RES_ON
	HAL_Delay(1);
	LCD_RES_OFF
	HAL_Delay(120);

	lcd_write_cmd(0x01); //软件复位
	HAL_Delay(5);

	lcd_write_cmd(0x11); //退出睡眠模式
	HAL_Delay(120);

	lcd_write_cmd(0x3A); //设置颜色通道
	lcd_write_dat8(0x55); //RGB565 16bit

//	lcd_write_cmd(0xB2); //设置前后廊
//	lcd_write_dat8(0x01);
//	lcd_write_dat8(0x01);
//	lcd_write_dat8(0x00);
//	lcd_write_dat8(0x33);
//	lcd_write_dat8(0x33);

//	lcd_write_cmd(0xC6); //更改刷新率
//	lcd_write_dat8(0x1F);

	lcd_write_cmd(0x21); //颜色反转

	lcd_write_cmd(0x29); //开启显示

}

void lcd_set_area(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2){

	lcd_write_cmd(0x2A); //设置列地址：x
	lcd_write_dat16(x1);
	lcd_write_dat16(x2);

	lcd_write_cmd(0x2B); //设置行地址：y
	lcd_write_dat16(y1);
	lcd_write_dat16(y2);

	lcd_write_cmd(0x2C); //指令：指示后面的数据写入显示RAM

}

void lcd_draw_area(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, uint16_t* color_map){

	lcd_set_area(x1, y1, x2, y2);

	LCD_CS_ON
	LCD_DC_DATA

	/* 方法1：SPI传输8bit，一个像素点需传两次 */
	for(uint32_t i=0; i<(x2 - x1 + 1)*(y2 - y1 + 1); i++){
		lcd_write_dat16(*color_map);
		color_map += 1;
	}



	/* 方法2：SPI传输8bit，一个像素点需传一次，一次传输 DMA_TRANS_COUNT 个 */
	/* 不能正常运行 ！ */
	/* 像素点的颜色显示出问题 —— 两个字节位置交错了 */
	/* DMA不工作 */
//	uint32_t dataSize = (x2 - x1 + 1) * (y2 - y1 + 1) * 2;
//
//	const uint16_t DMA_TRANS_COUNT = 65534;
//
//	uint8_t* dat_p = (uint8_t*)color_map;
//
//	while(dataSize){
//		if(dataSize > DMA_TRANS_COUNT){
////			HAL_SPI_Transmit_DMA(&hspi1, dat_p, DMA_TRANS_COUNT);
//			HAL_SPI_Transmit(&hspi1, dat_p, DMA_TRANS_COUNT, 100);
//			dataSize -= DMA_TRANS_COUNT;
//			dat_p += DMA_TRANS_COUNT;
//		}
//		else{
////			HAL_SPI_Transmit_DMA(&hspi1, dat_p, dataSize);
//			HAL_SPI_Transmit(&hspi1, dat_p, dataSize, 100);
//			dataSize = 0;
//		}
//	}



	LCD_CS_OFF

}
